package com.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/com")
public class HelloController {
    private static final String RESOURCE_NAME = "hello";
    private static final String USER_RESOURCE_NAME = "user";
    private static final String DEGRADE_RESOURCE_NAME = "degrade";

    @RequestMapping(value = "/hello")
    public String hello() {
        Entry entry = null;
        try {
            entry = SphU.entry(RESOURCE_NAME);//针对资源进行限制
            String str = "hello world";
            log.info("======" + str + "=====");
            return str;
        } catch (BlockException e) {
            //资源访问阻止 被限流或者被降级
            //进行相应的处理操作
            log.info("block");
            return "被流控了";

        } catch (Exception e) {
                 //记录异常
            Tracer.traceEntry(e, entry);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return "";
    }

    @PostConstruct
    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();//流控规则
        FlowRule rule = new FlowRule();//流控
        rule.setRefResource(RESOURCE_NAME);//设置受保护的资源 为哪个资源设置流控
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//设置受保护的资源阈值
        rule.setCount(1L);//set limit QPS to 20
        rules.add(rule);
        Object o=new Object();
        ArrayList arrayList=new ArrayList();

    }


}
